package com.coldworks.coldjoke.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.coldworks.coldjoke.R;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.umeng.socialize.bean.ShareImage;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.ULocation;
import com.umeng.socialize.common.InfoAgent;
import com.umeng.socialize.controller.SocializeController;
import com.umeng.socialize.controller.OauthHelper.SHARE_MEDIA;
import com.umeng.socialize.controller.listener.SocializeListeners.OauthCallbackListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.exception.SocializeException;

public class ShareManager {

	// 检测微信版本号，用于辨别是否支持朋友圈的分享
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	private static ShareManager instance = null;

	public static ShareManager getInstance() {
		if (instance == null) {
			synchronized (JokeDbManager.class) {
				if (instance == null) {
					instance = new ShareManager();
				}
			}
		}
		return instance;
	}

	private ShareManager() {

	}

	// 判断是否已经授权
	public boolean isOauthed(Context context, SHARE_MEDIA shareMedia) {
		if (InfoAgent.isOauthed(context, shareMedia)) {
			Toast.makeText(context, "已经授权.", Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

	// 进行授权
	public void doOauthVerify(final Context context,
			final SocializeController controller, final SHARE_MEDIA shareMedia,
			final String shareContent, final ShareImage shareImage,
			final ULocation uLocation) {
		controller.doOauthVerify(context, shareMedia,
				new OauthCallbackListener() {
					@Override
					public void onError(SocializeException e,
							SHARE_MEDIA platform) {
						Toast.makeText(context, R.string.err_connecting,
								Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onComplete(Bundle value, SHARE_MEDIA platform) {
						if (value != null
								&& !TextUtils.isEmpty(value.getString("uid"))) {
							Toast.makeText(context, "授权成功.", Toast.LENGTH_SHORT)
									.show();
							doShareToSocial(context, controller, shareMedia,
									shareContent, shareImage, uLocation);
						} else {
							Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT)
									.show();
						}
					}

				});
	}

	// 进行分享
	private void doShareToSocial(final Context context,
			final SocializeController controller, final SHARE_MEDIA shareMedia,
			final String shareContent, final ShareImage shareImage,
			final ULocation uLocation) {

		byte[] imageBytes;
		if (shareImage == null) {
			imageBytes = null;
		} else {
			imageBytes = shareImage.getImageBytes();
		}

		controller.postShare(context, shareContent, imageBytes, shareMedia,
				null, new SnsPostListener() {
					protected final Logger log = LoggerFactory.getLogger(this
							.getClass());

					@Override
					public void onStart() {
						Toast.makeText(context, "开始分享.", Toast.LENGTH_SHORT)
								.show();
					}

					@Override
					public void onComplete(SHARE_MEDIA platform, int eCode,
							SocializeEntity entity) {

						String eMsg = "";
						switch (eCode) {
						case 200:
							eMsg = "恭喜你，分享成功啦!";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							break;
						case -101:
							eMsg = "分享失败";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							log.info("share to " + shareMedia + " : "
									+ String.valueOf(eCode));
							break;
						case 5027:
							eMsg = "你的授权已经过期啦，重新授权再试试嘛！";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							doOauthVerify(context, controller, shareMedia,
									shareContent, shareImage, uLocation);
							break;
						case 5028:
							eMsg = "你的授权已经过期啦，重新授权再试试嘛！";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							doOauthVerify(context, controller, shareMedia,
									shareContent, shareImage, uLocation);
							break;
						case 5016:
							eMsg = "你分享的内容是重复的啊，换个笑话再分享嘛！";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							break;
						case 1000:
							eMsg = "真抱歉，出现了未知错误，稍后再分享嘛";
							Toast.makeText(context, eMsg, Toast.LENGTH_SHORT)
									.show();
							break;
						default:
							break;
						}
						log.info("share to " + String.valueOf(shareMedia)
								+ " : " + String.valueOf(eMsg));
					}
				});
	}

	// 分享到微信好友
	public void shareToWeixinPerson(Context context, IWXAPI api,
			String shareUrl, String shareTitle, String shareContent,
			Bitmap bitmap) {
		if (!api.isWXAppInstalled()) {
			Toast.makeText(context, R.string.weixin_not_installed,
					Toast.LENGTH_SHORT).show();
			return;
		}
		shareToWeixin(context, api, shareUrl, shareTitle, shareContent,
				SendMessageToWX.Req.WXSceneSession, bitmap);
	}

	// 分享到微信朋友圈
	public void shareToWeiXinFriend(Context context, IWXAPI api,
			String shareUrl, String shareTitle, String shareContent,
			Bitmap bitmap) {
		if (!api.isWXAppInstalled()) {
			Toast.makeText(context, R.string.weixin_not_installed,
					Toast.LENGTH_SHORT).show();
			return;
		}
		int wxSdkVersion = api.getWXAppSupportAPI();
		if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
			shareToWeixin(context, api, shareUrl, shareTitle, shareContent,
					SendMessageToWX.Req.WXSceneTimeline, bitmap);
		} else {
			Toast.makeText(context, "你的微信版本低于4.2，不支持朋友圈分享功能，你可选择分享至微信好友。",
					Toast.LENGTH_LONG).show();
		}
	}

	public void shareToWeixin(Context context, IWXAPI api, String shareUrl,
			String shareTitle, String shareContent, int scene, Bitmap thumbnail) {

		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = shareUrl;
		WXMediaMessage msg = new WXMediaMessage(webpage);

		if (thumbnail == null) {
			msg.setThumbImage(BitmapFactory.decodeResource(
					context.getResources(), R.drawable.ic_launcher));
		} else {
			msg.setThumbImage(thumbnail);
		}

		if (shareTitle != null) {
			msg.title = shareTitle;
		}
		if (shareContent != null) {
			msg.description = shareContent;
		}

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = scene;
		api.sendReq(req);
	}

	// 分享到短信
	public void shareToMMS(Context context, String content, String shareUrl,
			boolean hasImage) {

		String shareContent = null;

		if (!hasImage) {
			shareContent = content + " " + shareUrl + " 内容来自于爱讲冷笑话.";
		} else {
			shareContent = content + "[图片] " + shareUrl + " 内容来自于爱讲冷笑话.";
		}

		Intent it = new Intent(Intent.ACTION_VIEW);
		it.putExtra("sms_body", shareContent);
		it.setType("vnd.android-dir/mms-sms");
		context.startActivity(it);

	}

	// 分享到邮件
	public static void shareToEmail(Context context, String content,
			String filePath) {

	}

	// 分享到新浪微博
	public void shareToWeibo(Context context, SocializeController controller,
			String shareContent, ShareImage shareImage, ULocation uLocation) {
		doShareToSocial(context, controller, SHARE_MEDIA.SINA, shareContent,
				shareImage, uLocation);

	}

	// 分享到腾讯微博
	public void shareToTWeibo(Context context, SocializeController controller,
			String shareContent, ShareImage shareImage, ULocation uLocation) {
		doShareToSocial(context, controller, SHARE_MEDIA.TENCENT, shareContent,
				shareImage, uLocation);
	}

	// 分享到人人网
	public void shareToRenren(Context context, SocializeController controller,
			String shareContent, ShareImage shareImage, ULocation uLocation) {
		doShareToSocial(context, controller, SHARE_MEDIA.RENREN, shareContent,
				shareImage, uLocation);
	}

	// 分享到豆瓣
	public void shareToDouban(Context context, SocializeController controller,
			String shareContent, ShareImage shareImage, ULocation uLocation) {
		doShareToSocial(context, controller, SHARE_MEDIA.DOUBAN, shareContent,
				shareImage, uLocation);
	}

	// 分享到Qzone
	public void shareToQzone(Context context, SocializeController controller,
			String shareContent, ShareImage shareImage, ULocation uLocation) {
		doShareToSocial(context, controller, SHARE_MEDIA.QZONE, shareContent,
				shareImage, uLocation);
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}
}
